package com.qianchang.microfinance.setting;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.BaseDialogFragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.dm.library.utils.DateUtil;
import com.dm.library.utils.DensityUtil;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.utils.AppManager;
import com.qianchang.microfinance.view.MainActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: <描述内容>
 * 修 改 人: jiaohongyun
 * 修改时间: 2017/2/23
 */
public class DownLoadingDialog extends BaseDialogFragment {
    private static final String TAG = "DownLoadingDialog";


    private static DownLoadingDialog mInstance;
    @BindView(R.id.txt_alert_title)
    TextView     txtAlertTitle;
    @BindView(R.id.close_iv)
    ImageView    closeIv;
    @BindView(R.id.progress_tv)
    DTextView    progressTv;
    @BindView(R.id.progress_ll)
    LinearLayout progressLl;
    @BindView(R.id.pb_progress)
    ProgressBar  pbProgress;
    private RequestCall build;
    private boolean     canCancel;

    public static DownLoadingDialog newInstance(Bundle bundle) {
        if (mInstance == null) {
            mInstance = new DownLoadingDialog();
        }
        if (bundle != null) {
            mInstance.setArguments(bundle);
        }
        return mInstance;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Dialog dialog = getDialog();
        if (null != dialog) {
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            Window window = dialog.getWindow();
            if (null != window) {
                window.setBackgroundDrawableResource(android.R.color.transparent);
            }
        }
        View view = inflater.inflate(R.layout.downloading_app, container, false);
        ButterKnife.bind(this, view);
        if (null != closeIv) {
            if (canCancel) {
                closeIv.setVisibility(View.VISIBLE);
            } else {
                closeIv.setVisibility(View.GONE);
            }
        }
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        View view = getView();
        if (null != view) {
            int width = DensityUtil.getScreenWidth(getActivity());
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.width = (int) (width * 0.75);
            view.setLayoutParams(params);
        }
        setCancelable(false);
        Bundle arguments = getArguments();
        if (null != arguments) {
            String url = arguments.getString("url");
            downLoad(url);
        }
    }


    @OnClick(R.id.close_iv)
    public void onClick() {
        hideDialog();
    }


    public void hideDialog() {
        if (null != build) {
            Call call = build.getCall();
            if (call != null && !call.isCanceled()) {
                call.cancel();
            }
        }
        dismissAllowingStateLoss();
    }

    protected void downLoad(String url) {
        //        GetBuilder getBuilder = OkHttpUtils.get().url("http://www.wandoujia.com/apps/com.UCMobile/binding?source=web_inner_referral_binded");
        if (!TextUtils.isEmpty(url) && FormatUtil.validateUrl(url)) {
            GetBuilder getBuilder = OkHttpUtils.get().url(url);
            String fileName = "zhongjin_" + DateUtil.millis2String(System.currentTimeMillis(), new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())) + ".apk";
            build = getBuilder.build();
            build.execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), fileName) {
                @Override
                public void onError(Call call, Exception e, int i) {
                    ToastUtil.getInstant().show(getContext().getApplicationContext(), "更新失败");
                    hideDialog();
                }

                @Override
                public void inProgress(float progress, long total, int id) {
                    super.inProgress(progress, total, id);
                    float pb = progress * 100;
                    pbProgress.setProgress((int) (pb));
                    progressTv.setText((int) (pb) + "%");
                }


                @Override
                public void onResponse(File file, int i) {
                    hideDialog();
                    if (null != file && file.exists()) {
                        openFile(file);
                    }
                }
            });
        }
    }

    private void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(getContext().getApplicationContext(), "com.qianchang.microfinance.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        startActivity(intent);
        AppManager.getAppManager().finishOtherActivities(MainActivity.class);
    }

    public void canCancel(boolean canCancel) {
        this.canCancel = canCancel;
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}
